import { ElMessage } from "element-plus";
import api from "@/api";
import { ref, onMounted, watch, computed } from "vue";
import { useStore } from "vuex";
export default function homeRepository() {
  // 替代2.0 this.$refs.storeStyle获得dom
  const storeRef = ref(null);
  // 替代2.0 this.$store
  const store = useStore();
  const filterName = ref("");
  const pageSize = ref(10);
  const pageNum = ref(1);
  const id = ref("");
  const form = ref({ name: "", birth: "" });
  const dialogFormVisible = ref(false);
  const get = () => {
    store.commit("addCount");
    const name = filterName.value;
    store.dispatch("getData", {
      name,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
  };
  const del = (id) => {
    api.user.delUser(id).then((res) => {
      if (res.data.code == 200) {
        get();
      } else {
        ElMessage("操作失败");
      }
    });
  };
  const save = () => {
    if (!id.value) {
      api.user.addUser(form.value).then((res) => {
        if (res.data.code == 200) {
          get();
          dialogFormVisible.value = false;
        } else {
          ElMessage("操作失败");
        }
      });
    } else {
      api.user.updateUser(id.value, form.value).then((res) => {
        if (res.data.code == 200) {
          get();
          dialogFormVisible.value = false;
          id.value = "";
        } else {
          ElMessage("操作失败");
        }
      });
    }
  };
  const edit = (row) => {
    id.value = row.id;
    form.value.name = row.name;
    form.value.birth = row.birth;
    dialogFormVisible.value = true;
  };
  const cancel = () => {
    id.value = "";
    dialogFormVisible.value = false;
  };
  // 渲染后生命周期钩子
  onMounted(get);
  onMounted(() => {
    storeRef.value.style.color = "red";
  });
  // 监听属性
  watch(filterName, get);
  // 计算属性
  const nameCount = computed(() => {
    const count = tableData.value.filter(
      (t) => t.name.indexOf("张") != -1
    ).length;
    return count;
  });
  const storeCount = computed(() => {
    return store.state.count;
  });
  const tableData = computed(() => {
    return store.state.tableData;
  });
  const totalNum = computed(() => {
    return store.state.totalNum;
  });
  return {
    id,
    tableData,
    filterName,
    pageSize,
    pageNum,
    totalNum,
    form,
    dialogFormVisible,
    nameCount,
    storeCount,
    get,
    del,
    save,
    edit,
    cancel,
    storeRef,
  };
}
